package com.zozo.guanli.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        Object login = session.getAttribute("login");
        if (login != null && "login".equals(login.toString())) {
            //            login((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //        
        if (login != null && "start".equals(login.toString())) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        login((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    /**
     * 跳转到登录界面
     * 
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String redirect = request.getContextPath() + "/jsp/login.jsp";
        request.getSession().setAttribute("login", "login");
        (response).sendRedirect(redirect);
    }

}
